package com.briup.ch12;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

/**
 * @Author briup-adam
 * @Date 2023/10/25 下午5:25
 * @Description 聊天室的服务器
 **/

public class TcpServerDemo3 {
    public static void main(String[] args) {
        try {
            Scanner scanner = new Scanner(System.in);
            ServerSocket server = new ServerSocket(10086);
            System.out.println("服务器开启 等待客户端连接");
            while (true){
                Socket socket = server.accept();
                String ip = socket.getInetAddress().toString();
                System.out.println("有客户端"+ip+"来连接");
                InputStreamReader isr=new InputStreamReader(socket.getInputStream());
                BufferedReader br=new BufferedReader(isr);
                PrintWriter pw=new PrintWriter(socket.getOutputStream(),true);
                while (true){
                    //先接收消息
                    String content = br.readLine();
                    System.err.println(ip+":"+content);
                    if ("bye".equals(content))
                        break;
                    //发消息
                    String msg = scanner.next();
                    pw.println(msg);
                    System.out.println("我："+msg);
                    if ("bye".equals(msg))
                        break;
                }
                socket.shutdownOutput();
                socket.shutdownInput();
                socket.close();
                System.out.println("客户端"+ip+"结束会话!");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
